package com.example.joblinker.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.joblinker.common.Result;
import com.example.joblinker.dto.CreateReplyDTO;
import com.example.joblinker.dto.CreateTopicDTO;
import com.example.joblinker.dto.ForumSearchDTO;
import com.example.joblinker.service.ForumService;
import com.example.joblinker.util.JwtUtil;
import com.example.joblinker.vo.BoardVO;
import com.example.joblinker.vo.ReplyVO;
import com.example.joblinker.vo.TopicVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/forum")
public class ForumController {

    @Resource
    private ForumService forumService;

    @Resource
    private JwtUtil jwtUtil;

    /**
     * 获取论坛统计数据
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getForumStats() {
        Map<String, Object> stats = forumService.getForumStats();
        return Result.success(stats);
    }

    /**
     * 获取所有板块列表
     */
    @GetMapping("/boards")
    public Result<List<BoardVO>> getForumBoards() {
        List<BoardVO> boards = forumService.getAllBoards();
        return Result.success(boards);
    }

    /**
     * 获取热门话题
     */
    @GetMapping("/topics/hot")
    public Result<List<TopicVO>> getHotTopics(@RequestParam(defaultValue = "10") Integer limit) {
        List<TopicVO> topics = forumService.getHotTopics(limit);
        return Result.success(topics);
    }

    /**
     * 获取最新话题列表
     */
    @GetMapping("/topics/latest")
    public Result<Page<TopicVO>> getLatestTopics(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<TopicVO> topicPage = forumService.getLatestTopics(page, size);
        return Result.success(topicPage);
    }

    /**
     * 获取板块详情和话题列表
     */
    @GetMapping("/boards/{id}")
    public Result<Map<String, Object>> getBoardDetail(
            @PathVariable Long id,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String filter,
            @RequestParam(required = false) String keyword) {
        Map<String, Object> result = forumService.getBoardDetail(id, page, size, filter, keyword);
        return Result.success(result);
    }

    /**
     * 获取话题详情
     */
    @GetMapping("/topics/{id}")
    public Result<TopicVO> getTopicDetail(@PathVariable Long id, HttpServletRequest request) {
        Long userId = null;
        try {
            userId = jwtUtil.getUserIdFromRequest(request);
        } catch (Exception e) {
            // 用户未登录，不影响话题查看
        }
        TopicVO topic = forumService.getTopicDetail(id, userId);
        return Result.success(topic);
    }

    /**
     * 获取话题回复列表
     */
    @GetMapping("/topics/{id}/replies")
    public Result<Page<ReplyVO>> getTopicReplies(
            @PathVariable Long id,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(defaultValue = "time") String sort,
            HttpServletRequest request) {
        Long userId = null;
        try {
            userId = jwtUtil.getUserIdFromRequest(request);
        } catch (Exception e) {
            // 用户未登录，不影响回复查看
        }
        Page<ReplyVO> replyPage = forumService.getTopicReplies(id, page, size, sort, userId);
        return Result.success(replyPage);
    }

    /**
     * 创建新话题
     */
    @PostMapping("/topics")
    public Result<TopicVO> createTopic(@RequestBody @Valid CreateTopicDTO createTopicDTO, HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        TopicVO topic = forumService.createTopic(createTopicDTO, userId);
        return Result.success(topic);
    }

    /**
     * 更新话题
     */
    @PutMapping("/topics/{id}")
    public Result<TopicVO> updateTopic(
            @PathVariable Long id,
            @RequestBody @Valid CreateTopicDTO updateTopicDTO,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        TopicVO topic = forumService.updateTopic(id, updateTopicDTO, userId);
        return Result.success(topic);
    }

    /**
     * 删除话题
     */
    @DeleteMapping("/topics/{id}")
    public Result<Boolean> deleteTopic(@PathVariable Long id, HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        boolean success = forumService.deleteTopic(id, userId);
        return Result.success(success);
    }

    /**
     * 发表回复
     */
    @PostMapping("/replies")
    public Result<ReplyVO> createReply(@RequestBody @Valid CreateReplyDTO createReplyDTO, HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        ReplyVO reply = forumService.createReply(createReplyDTO, userId);
        return Result.success(reply);
    }

    /**
     * 删除回复
     */
    @DeleteMapping("/replies/{id}")
    public Result<Boolean> deleteReply(@PathVariable Long id, HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        boolean success = forumService.deleteReply(id, userId);
        return Result.success(success);
    }

    /**
     * 话题点赞
     */
    @PostMapping("/topics/{id}/like")
    public Result<Boolean> likeTopic(@PathVariable Long id, HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        boolean success = forumService.voteTopic(id, userId, true);
        return Result.success(success);
    }

    /**
     * 取消话题点赞
     */
    @PostMapping("/topics/{id}/unlike")
    public Result<Boolean> unlikeTopic(@PathVariable Long id, HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        boolean success = forumService.voteTopic(id, userId, false);
        return Result.success(success);
    }

    /**
     * 回复点赞
     */
    @PostMapping("/replies/{id}/like")
    public Result<Boolean> likeReply(@PathVariable Long id, HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        boolean success = forumService.voteReply(id, userId, true);
        return Result.success(success);
    }

    /**
     * 取消回复点赞
     */
    @PostMapping("/replies/{id}/unlike")
    public Result<Boolean> unlikeReply(@PathVariable Long id, HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        boolean success = forumService.voteReply(id, userId, false);
        return Result.success(success);
    }

    /**
     * 搜索话题
     */
    @GetMapping("/search")
    public Result<Page<TopicVO>> searchTopics(ForumSearchDTO searchDTO) {
        Page<TopicVO> topicPage = forumService.searchTopics(searchDTO);
        return Result.success(topicPage);
    }

    /**
     * 获取用户的话题列表
     */
    @GetMapping("/users/{userId}/topics")
    public Result<Page<TopicVO>> getUserTopics(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<TopicVO> topicPage = forumService.getUserTopics(userId, page, size);
        return Result.success(topicPage);
    }

    /**
     * 获取用户的回复列表
     */
    @GetMapping("/users/{userId}/replies")
    public Result<Page<ReplyVO>> getUserReplies(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<ReplyVO> replyPage = forumService.getUserReplies(userId, page, size);
        return Result.success(replyPage);
    }

    /**
     * 设置话题为精华
     */
    @PostMapping("/topics/{id}/essence")
    public Result<Boolean> setTopicEssence(
            @PathVariable Long id,
            @RequestBody Map<String, Boolean> body,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        Boolean isEssence = body.get("isEssence");
        if (isEssence == null) {
            return Result.error("参数错误");
        }
        boolean success = forumService.setTopicEssence(id, isEssence, userId);
        return Result.success(success);
    }

    /**
     * 设置话题置顶
     */
    @PostMapping("/topics/{id}/top")
    public Result<Boolean> setTopicTop(
            @PathVariable Long id,
            @RequestBody Map<String, Boolean> body,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        Boolean isTop = body.get("isTop");
        if (isTop == null) {
            return Result.error("参数错误");
        }
        boolean success = forumService.setTopicTop(id, isTop, userId);
        return Result.success(success);
    }
} 